package com.example.simplerpc.common.protocol;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @Classname: JavaSerializeMessageProtocol
 * @Description:
 * @Author: Stonffe
 * @Date: 2022/12/19 17:33
 */
public class JavaSerializeMessageProtocol implements MessageProtocol {
    private byte[] serialize(Object obj) throws Exception{
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(stream);
        outputStream.writeObject(obj);
        return stream.toByteArray();
    }
    @Override
    public byte[] marshallingReqest(RpcRequest request) throws Exception {
        return serialize(request);
    }

    @Override
    public RpcRequest unmarshallingRequest(byte[] data) throws Exception {
        ByteArrayInputStream stream = new ByteArrayInputStream(data);
        ObjectInputStream objectInputStream = new ObjectInputStream(stream);
        return ((RpcRequest) objectInputStream.readObject());
    }

    @Override
    public byte[] marshallingResponse(RpcResponse response) throws Exception {
        return serialize(response);
    }

    @Override
    public RpcResponse unmarshallingResponse(byte[] data) throws Exception {
        ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(data));
        return ((RpcResponse) stream.readObject());
    }
}
